/* 
 * Copyright (C) 2010 Christian Schneider
 * 
 * This file is part of NS2 news.
 * 
 * NS2 news is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NS2 news is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NS2 news.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */


package tritop.android.naturalselectionnews;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class TSAPad extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener, IGLOBALS{
    private static final String LOGTAG = "TSANEWSPAD";
    public static final String UPDATEINTENT="tritop.android.tsapad.UPDATE";
    public static final int UPDATETWEETTEXT=150;
    public static final int UPDATETWEET=100;
    public static final int UPDATESTATSREADY=200;
    private int mStatsInterval;
    private int mTweetInterval=60*1000*60;
    private int mStatsVersion;
	private WorkManager mWorkManager=null;
	private ViewFlipper mTweetFlipper;
	private ImageView mBtnVid,mBtnCam,mBtnChart,mBtnWww;
	private ProgressBar mProgressBarTweet,mProgressLoadingStats;
	private Handler mHandler;
	private SharedPreferences mSharedPref;
	

	
	private ServiceConnection mServiceConnection= new ServiceConnection(){
		
       @Override
       public void onServiceConnected(ComponentName name, IBinder service) {
			if(DEBUG_ON){
				Log.e(LOGTAG,"onServiceConntected");
			}
			mWorkManager = ((WorkManager.localBinder) service).getService();
			mWorkManager.setmNewestBuild(mStatsVersion);
			mWorkManager.setCallbackHandler(mHandler);
			updateStatsReady(mWorkManager.isUpdatingStats());
			updateTweetReady(mWorkManager.fetchTweets());
			setupUpdateTweetTimer();
	        setupUpdateStatsTimer();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mWorkManager = null;
		}
		
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        mSharedPref.registerOnSharedPreferenceChangeListener(this);
        mBtnCam = (ImageView) this.findViewById(R.id.imageViewCamBtn);
        mBtnChart= (ImageView) this.findViewById(R.id.imageViewChartBtn);
        mBtnWww= (ImageView) this.findViewById(R.id.imageViewWwwBtn);
        mBtnVid= (ImageView) this.findViewById(R.id.imageViewVideo);
        mProgressBarTweet = (ProgressBar) this.findViewById(R.id.progressBarTweet);
        mProgressLoadingStats= (ProgressBar) this.findViewById(R.id.progressBarLoadingStats);
        mTweetFlipper = (ViewFlipper) this.findViewById(R.id.viewFlipperTweets);
        mTweetFlipper.setInAnimation(this, R.anim.tweet_in);
        mTweetFlipper.setOutAnimation(this, R.anim.tweet_out);
        
        mBtnVid.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				showVideo();
			}
        });
        mBtnCam.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				showGallery();
			}
        });
        mBtnChart.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				showStats();
			}
        });
        mBtnWww.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				showWebsite();
			}
        });
        
        setupHandler();
        //Debug.startMethodTracing();
    }
    
    
    @Override
	protected void onDestroy() {
		//Debug.stopMethodTracing();
    	mSharedPref.unregisterOnSharedPreferenceChangeListener(this);
		super.onDestroy();
	}


	@Override
	protected void onPause() {
		if(DEBUG_ON){
			Log.e(LOGTAG,"onPause");
		}
		if(mWorkManager!=null){
			mWorkManager.closeDb();
		}
		unbindService(mServiceConnection);
		super.onPause();
	}


	@Override
	protected void onResume() {
		if(DEBUG_ON){
			Log.e(LOGTAG,"onResume");
		}
		mStatsInterval=Integer.valueOf(mSharedPref.getString("prefStatsUpdateInterval", "12"))*1000*60*60;
		mTweetInterval=Integer.valueOf(mSharedPref.getString("prefTweetUpdateInterval", "1"))*1000*60*60;
		mStatsVersion=Integer.valueOf(mSharedPref.getString("prefBuildVersion", String.valueOf(NEWESTBUILD)));
		if(mStatsVersion<NEWESTBUILD){
			if(DEBUG_ON){
				Log.e(LOGTAG,"overloading build version");
			}
			mStatsVersion=NEWESTBUILD;
			SharedPreferences.Editor editor = mSharedPref.edit();
			editor.putString("prefBuildVersion", String.valueOf(mStatsVersion));
			editor.commit();
		}
		connectToService();
		if(mWorkManager!=null){
			mWorkManager.setmNewestBuild(mStatsVersion);
			mWorkManager.setCallbackHandler(mHandler);
		}
		super.onResume();
	}

	
	//*************************************************************************
	// Inflate Menu from resource
	//*************************************************************************
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inf = this.getMenuInflater();
		inf.inflate(R.menu.optionsmenu, menu);
		return super.onCreateOptionsMenu(menu);
	}


	//*************************************************************************
	// connect menu items to functions
	//*************************************************************************
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
			case R.id.itemQuit: finish();break;
			case R.id.itemPreferences:showPreferenceScreen();break;
			//case R.id.itemdbexport:exportDB();break; debug
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	//*************************************************************************
	// bind app to workmanager service
	//*************************************************************************
	
	public void connectToService(){
		if(DEBUG_ON){
			Log.e(LOGTAG,"connect to service");
		}
    	Intent intent = new Intent(this,WorkManager.class);
    	bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    }
	
	private void updateStats(){
		if(mWorkManager!=null){
			mWorkManager.updateStatsData();
		}
	}
    
	
	//*************************************************************************
	//setup timer to update stats
	//*************************************************************************
	
	private void setupUpdateStatsTimer(){
		if(DEBUG_ON){
			Log.e(LOGTAG,"setupUpdateStatsTimer() called");
		}
		Intent intent = new Intent(UPDATEINTENT);
		intent.putExtra("TASK", WorkManager.TASK_UPDATE_STATS);
		PendingIntent penIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 555555, intent, PendingIntent.FLAG_NO_CREATE);
		if(penIntent==null){
			if(DEBUG_ON){
				Log.e(LOGTAG,"setupUpdateStatsTimer() new intent called");
			}
			penIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 555555, intent, PendingIntent.FLAG_CANCEL_CURRENT);
			AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), mStatsInterval, penIntent);
		}
	}
	
	//*************************************************************************
	//remove timer to update stats
	//*************************************************************************
	
	private void killUpdateStatsTimer(){
		if(DEBUG_ON){
			Log.e(LOGTAG,"killUpdateStatsTimer() called");
		}
		Intent intent = new Intent(UPDATEINTENT);
		intent.putExtra("TASK", WorkManager.TASK_UPDATE_STATS);
		PendingIntent penIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 555555, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
		alarmManager.cancel(penIntent);
		penIntent.cancel();
	}
	
	
	//*************************************************************************
	//setup timer to update tweets
	//*************************************************************************
	
	private void setupUpdateTweetTimer(){
		if(DEBUG_ON){
			Log.e(LOGTAG,"setupUpdateTweetTimer() called");
		}
		Intent intent = new Intent(UPDATEINTENT);
		intent.putExtra("TASK", WorkManager.TASK_UPDATE_TWEET);
		PendingIntent penIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 555565, intent, PendingIntent.FLAG_NO_CREATE);
		if(penIntent==null){
			if(DEBUG_ON){
				Log.e(LOGTAG,"setupUpdateTweetTimer() called");
			}
			penIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 555565, intent, PendingIntent.FLAG_CANCEL_CURRENT);
			AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), mTweetInterval, penIntent);
		}
	}
	
	//*************************************************************************
	//remove update tweets timer
	//*************************************************************************
	
	private void killUpdateTweetTimer(){
		if(DEBUG_ON){
			Log.e(LOGTAG,"killUpdateTweetTimer() called");
		}
		Intent intent = new Intent(UPDATEINTENT);
		intent.putExtra("TASK", WorkManager.TASK_UPDATE_TWEET);
		PendingIntent penIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 555565, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
		alarmManager.cancel(penIntent);
		penIntent.cancel();
	}
	
	//*************************************************************************
	//this handler will be called from workmanager service if something happens
	//*************************************************************************
	
	private void setupHandler(){
		mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what){
					case UPDATETWEETTEXT: mProgressBarTweet.setVisibility(View.GONE);updateTweetReady(((String[] )msg.obj)); break;
					case UPDATETWEET:mProgressBarTweet.setVisibility(View.VISIBLE);break;
					case UPDATESTATSREADY:updateStatsReady((msg.arg1==0)?false:true);break;
					default:break;
				}
			}
			
		};
	}
	
	private void updateStatsReady(boolean isWorking){
		if(DEBUG_ON){
			Log.e(LOGTAG,"updateStats Ready "+isWorking);
		}
		if(!isWorking){
			mProgressLoadingStats.setVisibility(View.GONE);
			mBtnChart.setVisibility(View.VISIBLE);
		}
		else {
			mBtnChart.setVisibility(View.GONE);
			mProgressLoadingStats.setVisibility(View.VISIBLE);
		}
	}
	
	
	//*************************************************************************
	//tweets received, now show them
	//*************************************************************************
	
	private void updateTweetReady(String[] tweets){
		if(DEBUG_ON){
			Log.e(LOGTAG,"updating tweets"+tweets.length);
		}
		//mProgressBarTweet.setVisibility(View.GONE);
		mTweetFlipper.removeAllViews();
		for(String tweet: tweets){
			TextView tweetView = new TextView(this);
			tweetView.setTextColor(getResources().getColor(R.color.TweetTextColor));
			tweetView.setLinkTextColor(getResources().getColor(R.color.TweetTextLinkColor));
			tweetView.setBackgroundColor(getResources().getColor(R.color.TweetTextBackgroundColor));
			tweetView.setText(tweet);
			Linkify.addLinks(tweetView, Linkify.WEB_URLS);
			mTweetFlipper.addView(tweetView);
		}
		mTweetFlipper.setFlipInterval(6000);
		mTweetFlipper.startFlipping();
	}
	
	
	//*************************************************************************
	//export DB to sd card (debug)
	//*************************************************************************
	
	private void exportDB(){
		if(mWorkManager!=null){
			mWorkManager.exportDb();
		}
	}
    
	
	//*************************************************************************
	//start preferenc activity
	//*************************************************************************
	
	private void showPreferenceScreen(){
		Intent intent = new Intent(this,Preferences.class);
		this.startActivity(intent);
	}
	
	
	//*************************************************************************
	//start chart activity, items are put in bundel
	//*************************************************************************
	
	private void showStats(){
		Bundle bundel = new Bundle();
		Intent intent = new Intent(this,StatsVisualizer.class);
		int marineWins=(int) mWorkManager.getWins(1, mStatsVersion);
		int khaaraWins=(int) mWorkManager.getWins(2, mStatsVersion);
		ContentValues values = new ContentValues();
		values.put("Marines", marineWins);
		values.put("Khaara", khaaraWins);
		bundel.putParcelable(StatsVisualizer.VISVALUES, values);
		bundel.putInt(StatsVisualizer.BUILDVERSION, mStatsVersion);
		intent.putExtras(bundel);
		this.startActivity(intent);
	}
	
	
	//*************************************************************************
	//open Wallpaper gallery
	//*************************************************************************
	
	private void showGallery(){
		Intent intent = new Intent(this,PicGallery.class);
		this.startActivity(intent);
	}
	
	
	//*************************************************************************
	//start video channel
	//*************************************************************************
	
	private void showVideo(){
		  String url = "http://www.youtube.com/unknownworlds";  
		  Intent intent = new Intent(Intent.ACTION_VIEW);  
		  intent.setData(Uri.parse(url));  
		  startActivity(intent);  
	}
	
	//*************************************************************************
	//show ns2 website
	//*************************************************************************
	
	private void showWebsite(){
		  String url = "http://www.unknownworlds.com/ns2/";  
		  Intent intent = new Intent(Intent.ACTION_VIEW);  
		  intent.setData(Uri.parse(url));  
		  startActivity(intent);  
	}

	
	//*************************************************************************
	//user changed some preferences now reset update timers
	//*************************************************************************
	
	@Override
	public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
		if(DEBUG_ON){
			Log.e(LOGTAG,"Preference "+key+" changed");
		}
		if(key.equals("prefStatsUpdateInterval")){
			mStatsInterval=Integer.valueOf(mSharedPref.getString("prefStatsUpdateInterval", "3"))*1000*60*60;
			killUpdateStatsTimer();
			if(mStatsInterval>0){
				setupUpdateStatsTimer();
			}
		}
		else if(key.equals("prefTweetUpdateInterval")){
			mTweetInterval=Integer.valueOf(mSharedPref.getString("prefTweetUpdateInterval", "1"))*1000*60*60;
			killUpdateTweetTimer();
			if(mTweetInterval>0){
				setupUpdateTweetTimer();
			}
		}
		
	}
}